<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <h2>注册 AirShare</h2>
        <p>创建您的文件分享账户</p>
      </div>
      
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-width="0px"
        class="register-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            type="text"
            placeholder="用户名（3-50个字符）"
            prefix-icon="User"
            size="large"
            @blur="checkUsernameAvailability"
          />
        </el-form-item>
        
        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            type="email"
            placeholder="邮箱地址"
            prefix-icon="Message"
            size="large"
            @blur="checkEmailAvailability"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="密码（至少6位）"
            prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>
        
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="确认密码"
            prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>
        
        <el-form-item prop="verificationCode">
          <div class="verification-input">
            <el-input
              v-model="registerForm.verificationCode"
              type="text"
              placeholder="邮箱验证码"
              prefix-icon="Key"
              size="large"
              class="code-input"
            />
            <el-button
              type="primary"
              size="large"
              :disabled="!canSendCode || codeCountdown > 0"
              :loading="sendingCode"
              @click="sendVerificationCode"
              class="send-code-btn"
            >
              {{ getCodeButtonText }}
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="registering"
            @click="handleRegister"
            class="register-btn"
          >
            {{ registering ? '注册中...' : '注册' }}
          </el-button>
        </el-form-item>
        
        <div class="register-footer">
          <router-link to="/login" class="login-link">
            已有账号？立即登录
          </router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Key } from '@element-plus/icons-vue'
import { register, sendVerificationCode as sendCode, checkUsername, checkEmail } from '@/apis/user'

const router = useRouter()

// 表单数据
const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  verificationCode: ''
})

// 表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度为3-50个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: '用户名只能包含字母、数字、下划线和中文', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 100, message: '密码长度为6-100位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入邮箱验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

// 确认密码验证器
function validateConfirmPassword(rule, value, callback) {
  if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 状态管理
const registering = ref(false)
const sendingCode = ref(false)
const codeCountdown = ref(0)
const registerFormRef = ref()
const usernameChecked = ref(false)
const emailChecked = ref(false)

// 计算属性
const canSendCode = computed(() => {
  return registerForm.email && 
         /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email) &&
         emailChecked.value
})

const getCodeButtonText = computed(() => {
  if (sendingCode.value) return '发送中...'
  if (codeCountdown.value > 0) return `${codeCountdown.value}s`
  return '发送验证码'
})

// 检查用户名可用性
const checkUsernameAvailability = async () => {
  if (!registerForm.username || registerForm.username.length < 3) {
    usernameChecked.value = false
    return
  }
  
  try {
    const response = await checkUsername(registerForm.username)
    if (response.code === 200) {
      if (response.data) {
        // 用户名可用
        usernameChecked.value = true
        ElMessage.success('用户名可用')
      } else {
        // 用户名已存在
        usernameChecked.value = false
        ElMessage.warning('用户名已存在')
      }
    }
  } catch (error) {
    console.error('Check username error:', error)
    usernameChecked.value = false
  }
}

// 检查邮箱可用性
const checkEmailAvailability = async () => {
  if (!registerForm.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email)) {
    emailChecked.value = false
    return
  }
  
  try {
    const response = await checkEmail(registerForm.email)
    if (response.code === 200) {
      if (response.data) {
        // 邮箱可用
        emailChecked.value = true
        ElMessage.success('邮箱可用')
      } else {
        // 邮箱已注册
        emailChecked.value = false
        ElMessage.warning('邮箱已被注册')
      }
    }
  } catch (error) {
    console.error('Check email error:', error)
    emailChecked.value = false
  }
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!canSendCode.value) {
    ElMessage.warning('请先输入有效的邮箱地址')
    return
  }
  
  try {
    sendingCode.value = true
    const response = await sendCode({ email: registerForm.email })
    
    if (response.code === 200) {
      ElMessage.success('验证码已发送，请查收邮件')
      startCountdown()
    } else {
      ElMessage.error(response.message || '发送验证码失败')
    }
  } catch (error) {
    console.error('Send verification code error:', error)
    ElMessage.error(error.message || '发送验证码失败，请稍后重试')
  } finally {
    sendingCode.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  codeCountdown.value = 60
  const timer = setInterval(() => {
    codeCountdown.value--
    if (codeCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    const valid = await registerFormRef.value.validate()
    if (!valid) return
    
    if (!usernameChecked.value) {
      ElMessage.warning('请先检查用户名是否可用')
      return
    }
    
    if (!emailChecked.value) {
      ElMessage.warning('请先检查邮箱是否可用')
      return
    }
    
    registering.value = true
    
    const { confirmPassword, ...registerData } = registerForm
    const response = await register(registerData)
    
    if (response.code === 200) {
      ElMessage.success('注册成功！请登录')
      router.push('/login')
    } else {
      ElMessage.error(response.message || '注册失败')
    }
  } catch (error) {
    console.error('Register error:', error)
    ElMessage.error(error.message || '注册失败，请稍后重试')
  } finally {
    registering.value = false
  }
}
</script>

<style scoped>
.register-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  box-sizing: border-box;
  margin: 0;
}

.register-box {
  width: 450px;
  max-width: 90vw;
  background: white;
  border-radius: 10px;
  padding: 40px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-header h2 {
  color: #333;
  margin-bottom: 10px;
  font-size: 28px;
}

.register-header p {
  color: #666;
  font-size: 14px;
}

.register-form {
  width: 100%;
}

.verification-input {
  display: flex;
  gap: 10px;
  align-items: stretch;
}

.code-input {
  flex: 1;
}

.code-input :deep(.el-input__wrapper) {
  height: 40px;
}

.send-code-btn {
  height: 40px;
  width: 120px;
  flex-shrink: 0;
  font-size: 13px;
  padding: 0 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.register-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  margin-top: 10px;
}

.register-footer {
  text-align: center;
  margin-top: 20px;
}

.login-link {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
}

.login-link:hover {
  text-decoration: underline;
}

.el-form-item {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  padding: 12px 15px;
  height: 40px;
  box-sizing: border-box;
}
</style>